package com.global.college.api;

import android.content.Intent;
import android.os.Looper;
import android.util.Log;

import com.global.college.CollegeApplication;
import com.global.college.UserData;
import com.global.college.ui.activity.LoginByPswActivity;
import com.global.college.utils.StringUtils;
import com.global.college.utils.ToastUtils;

import rx.functions.Func1;

/**
 * Created by fu on 2020/2/18.
 * Describe:
 * 功能函数--：获取网络数据的处理的
 * RxJava Retrofit2 网络请求，返回数据格式统一的数据报文处理方法：继承Func1类,重载里面的call方法
 * HttpResult<T>--参数，T结果
 * Func2<T1，T2,R>
 * Func3<T1，T2,T3,R>
 * Map数据转换处理
 */

public class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {

    @Override
    public T call(HttpResult<T> tHttpResult) {
        if (!"200".equals(tHttpResult.code)) {
            Log.w("HttpResultFunc", "tHttpResult.msg:" + tHttpResult.msg + "tHttpResult.result:" + tHttpResult.result);
            if (StringUtils.equals("401", tHttpResult.code)) {
                //清空用户缓存数据
                UserData.getInstance().ClearAllCachData();
                CollegeApplication.getContext().getApplicationContext().startActivity(new Intent(CollegeApplication.getContext().getApplicationContext(), LoginByPswActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                Looper.prepare();
                ToastUtils.showCenterToast("用户信息失效，请重新登录");
                Looper.loop();
            }
            //非正常返回结构处理
            throw new ApiException(tHttpResult.code, tHttpResult.msg);
        }
        return tHttpResult.result;
    }
}
